/*
 * Singularity Engine
 * Copyright (C) 2010 Vyacheslav Vorobyov, All rights reserved.
 * See LICENSE for full license information.
 */
package org.singularity.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.singularity.io.DME.Code;

/**
 * @author vjache
 * 
 */
public class InputLinesInFile<VT> implements Input<VT> {

	private final Code _code;
	private final File _file;

	/**
	 * 
	 */
	public InputLinesInFile(DME.Code aCode, File aFile) {
		_code = aCode;
		_file = aFile;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.singularity.io.Input#iterator()
	 */
	@Override
	public CloseableIterator<DME<VT>> iterator() {
		try {
			final RandomAccessFile _raf = new RandomAccessFile(_file, "rw");
			final String first = _raf.readLine();
			return new CloseableIterator<DME<VT>>() {

				@Override
				public void close() throws IOException {
					_raf.close();
				}

				private String _next = first;
				@Override
				public void remove() {}
				
				@Override
				public DME<VT> next() {
					DME<VT> n;
					try {
						n = new DMEImpl<VT>(_code,lineToValue(_next));
						_next = _raf.readLine();
						if(_next==null)
							_raf.close();
					} catch (IOException e) {
						try {
							_raf.close();
						} catch (IOException e1) {}
						throw new RuntimeException(e);
					}
					return n;
				}

				@Override
				public boolean hasNext() {
					return _next!=null;
				}
			};
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	protected VT lineToValue(String next) {
		return (VT)next;
	}

}
